#! -*- coding:utf-8 -*-
import os
import json
import logging
from datetime import datetime, timedelta

from common.stats import MG_BIGBANG_COLL as mg
from common.utils.tz import get_utc_date, local_now, utc_to_local


def create_kfc_report(day, new_user_id_list):
    # slot相关
    end = day + timedelta(days=1)
    # 总投注次数，开奖金额，投注金额
    group = {'_id': None}
    for k in ('bet_count', 'award_count', 'award_amount', 'bet_amount',
        'sp_count', 'sp_award'):
        group[k] = {'$sum': '$kfc.%s' % k}
    result = {'user_id_list': {}}
    # 总参与人数
    updated_filter = {'$gte': day, '$lt': end}
    t = mg.daily_stats.aggregate([
        {'$match': {'updated_at': updated_filter, 'kfc': {'$exists': True}}},
        {'$group': {'_id': None, 'user_id_list': {'$push': '$user_id'}}}
    ])
    t = t.next() if t.alive else {}
    result['user_id_list']['bet_user_id'] = t.get('user_id_list', [])
    result['real_user_count'] = len(t.get('user_id_list', []))
    # 总中奖次数， 元宝数
    t = mg.daily_stats.aggregate([
        {'$match': {'updated_at': updated_filter}},
        {'$group': group}
    ])
    t = t.next() if t.alive else {}
    result.update(t)
    # 盈利用户数、元宝数
    t = mg.daily_stats.aggregate([
        {'$match': {'$and': [
            {'updated_at': updated_filter},
            {'kfc.gain_amount': {'$gt': 0}}
        ]}},
        {'$group': {'_id': None, 'count': {'$sum': 1},
                    'amount': {'$sum': '$kfc.gain_amount'},
                    'user_id_list': {'$push': '$user_id'}}}
    ])
    t = t.next() if t.alive else {}
    result['gain_count'] = t.get('count', 0)
    result['gain_amount'] = t.get('amount', 0)
    result['user_id_list']['gain_user_id'] = t.get('user_id_list', [])
    # 亏损用户数， 亏损金额
    t = mg.daily_stats.aggregate([
        {'$match': {'$and': [
            {'updated_at': updated_filter},
            {'kfc.gain_amount': {'$lt': 0}}
        ]}},
        {'$group': {'_id': None, 'count': {'$sum': 1},
                    'amount': {'$sum': '$kfc.gain_amount'},
                    'user_id_list': {'$push': '$user_id'}}}
    ])
    t = t.next() if t.alive else {}
    result['lose_count'] = t.get('count', 0)
    result['lose_amount'] = t.get('amount', 0)
    result['user_id_list']['lose_user_id'] = t.get('user_id_list', [])
    # 投注分布
    group = {'_id': None}
    for k in range(3):
        for suffix in 'count', 'bet', 'award':
            field = 'gamestatus_%s_%s' % (k+1, suffix)
            group[field] = {'$sum': '$kfc.%s' % field}
    for k in (0.1, 1, 10, 100):
        field = 'amount_%s' % k
        if k == 0.1:
            field_key = 'amount_0'
        else:
            field_key = field
        group[field_key] = {'$sum': '$kfc.%s' % field}
    t = mg.daily_stats.aggregate([
        {'$match': {'updated_at': updated_filter}},
        {'$group': group}
    ])
    t = t.next() if t.alive else {}
    result.update(t)
    # 不同模式下参与人数
    for k in range(3):
        field = 'gamestatus_%s_count' % (k+1)
        result['gamestatus_%s_user_count' % (k+1)] = mg.daily_stats.count({
            'updated_at': updated_filter, 'kfc.%s' % field: {'$exists': True}}) or 0
    # 命中洪福七天的人数
    result['sp_user_count'] = mg.daily_stats.count({
        'updated_at': updated_filter, 'kfc.sp_count': {'$exists': True}}) or 0
    if result.get('bet_amount'):
        result['profit_rate'] = (
            result['bet_amount'] - result['award_amount']) / float(
            result['bet_amount'])
    result.pop('_id', None)

    result['new_user'] = {'user_id_list': {}}
    # 新用户盈利用户数、元宝数
    t = mg.daily_stats.aggregate([
        {'$match': {'$and': [
            {'updated_at': updated_filter},
            {'kfc.gain_amount': {'$gt': 0}},
            {'user_id': {'$in': new_user_id_list}}
        ]}},
        {'$group': {'_id': None, 'count': {'$sum': 1},
                    'amount': {'$sum': '$kfc.gain_amount'},
                    'bet': {'$sum': '$kfc.bet_amount'},
                    'win': {'$sum': {'$add': ["$kfc.gain_amount", "$kfc.bet_amount"]}},
                    'user_id_list': {'$push': '$user_id'}}}
    ])
    t = t.next() if t.alive else {}

    gain_total_bet = t.get('bet', 0)
    gain_total_win = t.get('win', 0)
    result['new_user']['gain_count'] = t.get('count', 0)
    result['new_user']['gain_amount'] = t.get('amount', 0)
    result['new_user']['user_id_list']['gain_user_id'] = t.get('user_id_list', [])
    # 亏损用户数， 亏损金额
    t = mg.daily_stats.aggregate([
        {'$match': {'$and': [
            {'updated_at': updated_filter},
            {'kfc.gain_amount': {'$lt': 0}},
            {'user_id': {'$in': new_user_id_list}}
        ]}},
        {'$group': {'_id': None, 'count': {'$sum': 1},
                    'amount': {'$sum': '$kfc.gain_amount'},
                    'bet': {'$sum': '$kfc.bet_amount'},
                    'win': {'$sum': {'$add': ["$kfc.gain_amount", "$kfc.bet_amount"]}},
                    'user_id_list': {'$push': '$user_id'}}}
    ])
    t = t.next() if t.alive else {}
    result['lose_count'] = t.get('count', 0)
    result['lose_amount'] = t.get('amount', 0)
    lose_total_bet = t.get('bet', 0)
    lose_total_win = t.get('win', 0)
    result['new_user']['lose_count'] = t.get('count', 0)
    result['new_user']['lose_amount'] = t.get('amount', 0)
    result['new_user']['user_id_list']['lose_user_id'] = t.get('user_id_list', [])

    result['new_user']['bet_amount'] = gain_total_bet + lose_total_bet
    if gain_total_bet + lose_total_bet:
        result['new_user']['profit_rate'] = (((gain_total_bet + lose_total_bet) - (gain_total_win + lose_total_win)) /
                                             (gain_total_bet + lose_total_bet))
    else:
        result['new_user']['profit_rate'] = 0
    result['new_user']['real_user_count'] = result['new_user']['gain_count'] + result['new_user']['lose_count']
    result['new_user']['user_id_list']['bet_user_id'] = list(set(result['new_user']['user_id_list']['lose_user_id']
                                                                 + result['new_user']['user_id_list']['gain_user_id']))
    mg.kfc_report.update_one(
        {'_id': utc_to_local(day).strftime('%Y-%m-%d')},
        {'$set': result}, upsert=True)
